package linkwechat.secirityhandler;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsUtils;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class SecutiryConfig extends WebSecurityConfigurerAdapter {

    // 认证成功的处理器
    @Resource
    SuccessHandler successHandler;

    // 认证失败的处理器
    @Resource
    LoseHandler loseHandler;

    // 用户配置类
    @Resource
    UserConfig userConfig;

    //用户请求过程中的异常处理器
    @Resource
    AuthentPoint authentPoint;

    // 访问受保护的资源时被拒绝抛出
    @Resource
    AccessHandler accessHandler;

    // 退出登录后的处理器
    @Resource
    LogoutHandler logoutHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest);

        http.formLogin()
                // 认证成功的处理器
                .successHandler(successHandler)
                // 认证失败的处理器
                .failureHandler(loseHandler)
                .permitAll()
                .and()
                .authorizeRequests() // 允许以下请求直接访问
                .antMatchers("/**")
                .permitAll()
                .and()
                // 授权通过身份认证的请求
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                // 异常处理处理器
                .exceptionHandling()
                // 处理用户请求过程中的异常
                .authenticationEntryPoint(authentPoint)
                // 访问受保护的资源时被拒绝抛出
                .accessDeniedHandler(accessHandler)
                .and()
                .logout()
                .logoutSuccessHandler(logoutHandler)
                .permitAll()
                .and()
                .csrf()
                .disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //        用户正确的详情信息  加密处理
        auth.userDetailsService(userConfig)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}
